package vn.edu.hut.soict.alignment;

import java.util.ArrayList;

public class AlignmentReverser {
	private String source;
	private String destination;
	private String alignment;
	private String reversedAlignment;

	public AlignmentReverser(String source, String alignment) {
		this.source = source;
		this.alignment = alignment;
		reversedAlignment = reverse();
	}

	private String reverse() {
		AlignmentParser parser = new AlignmentParser(alignment);
		String[] sourceSplit = source.split(" ");
		ArrayList<String> des = new ArrayList<String>();

		ArrayList<ArrayList<Integer>> reverse = new ArrayList<ArrayList<Integer>>(parser.destinationSize() + 1);
		for (int i = 0; i <= parser.destinationSize(); i++) {
			reverse.add(new ArrayList<Integer>());
			des.add(null);
		}

		for (int i = 0; i <= sourceSplit.length; i++) {
			int[] align = parser.alignmentIndex(i);
			String[] destinations = parser.alignmentString(i);
			if (align != null) {
				for (int j = 0; j < align.length; j++) {
					reverse.get(align[j]).add(i);
					if (des.get(align[j]) == null) {
						des.set(align[j], destinations[j]);
					}
				}
			}
		}

		if (reverse.get(reverse.size() - 1).size() == 0) {
			reverse.remove(reverse.size() - 1);
		}

		StringBuilder sb = new StringBuilder();
		for (String s : des) {
			if (s != "" && s != null) {
				sb.append(s).append(" ");
			}
		}
		sb.deleteCharAt(sb.length() - 1);
		destination = sb.toString();

		sb = new StringBuilder();
		for (int i = 0; i < reverse.size(); i++) {
			sb.append(i);
			for (Integer t : reverse.get(i)) {
				sb.append("#").append(t).append("|");
				if (t < sourceSplit.length) {
					sb.append(sourceSplit[t]);
				}
			}
			sb.append(" ");
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}

	public String destination() {
		return destination;
	}

	public String reversedAlignment() {
		return reversedAlignment;
	}
}
